<template>
  <div class="login">
    <div class="swiper">
      <div class="swiper-item mobile" :class="{ 'active': active === 1 }" @click="active = 1">
        手机快捷登录
      </div>
      <div class="swiper-item account" :class="{ 'active': active === 2 }" @click="active = 2">
        账号密码登录
      </div>
    </div>

    <!-- 手机号登录 -->
    <div v-show="active === 1" class="mobile-login-form-wrap">
      <m-form ref="form1" :model="mobileFormData" :rules="rules" style="width: 439px;">
        <m-form-item prop="mobile">
          <m-input ref="phone" v-model="mobileFormData.mobile" maxlength='11' placeholder="请输入手机号码">
            <img slot="prefix" src="~/assets/images/login-mobile-icon.png" alt=""
                 style="width: 15px; height: 22px;">
          </m-input>
        </m-form-item>

        <m-form-item prop="msg">
          <div style="width: 100%; display: flex; justify-content: space-between;">
            <m-input style="width: 300px;" v-model="mobileFormData.msg" placeholder="请输入短信验证码">
              <img slot="prefix" src="~/assets/images/login-msg-icon.png" alt=""
                   style="width: 16px; height: 14px;">
            </m-input>
            <m-button :disabled="flag" @click="phoneCaptcha()" width="130">{{ content }}</m-button>
          </div>
        </m-form-item>

        <m-form-item prop="verify">
          <div style="width: 100%; display: flex; justify-content: space-between;">
            <m-input style="width: 300px;" v-model="mobileFormData.verify" placeholder="请输入验证码">
              <img slot="prefix" src="~/assets/images/login-verify-icon.png" alt=""
                   style="width: 16px; height: 20px;">
            </m-input>
            <img @click="imgCaptcha()" class="captchaimg verify" :src="userInfo.imgurl" alt="">
          </div>
        </m-form-item>

        <div class="forget">
          <router-link to="/login-register/forget">忘记密码？</router-link>
        </div>

        <m-form-item>
          <div style="display: flex; justify-content: center;">
            <m-button width="235" @click="mobileLogin">登录</m-button>
          </div>
        </m-form-item>
      </m-form>
      <router-link to="/login-register/register" class="to-register">没有账号？立即注册</router-link>
      <router-link to="" class="scan-login" @click.native="goWXLogin">
        <img src="~/assets/images/wechat1.png" alt="">微信扫码登录
      </router-link>
    </div>

    <!-- 账号登录 -->
    <div v-show="active === 2" class="account-login-wrap">
      <m-form ref="form2" :model="accountFormData" :rules="rules" style="width: 439px;">
        <m-form-item prop="mobile">
          <m-input v-model="accountFormData.mobile" placeholder="请输入用户名或邮箱">
            <img slot="prefix" src="~/assets/images/login-mobile-icon.png" alt=""
                 style="width: 15px; height: 22px;">
          </m-input>
        </m-form-item>

        <m-form-item prop="password">
          <m-input v-model="accountFormData.password" placeholder="请输入密码" type="password">
            <img slot="prefix" src="~/assets/images/login-password-icon.png" alt=""
                 style="width: 16px; height: 20px;">
          </m-input>
        </m-form-item>

        <m-form-item prop="verify">
          <div style="width: 100%; display: flex; justify-content: space-between;">
            <m-input style="width: 300px;" v-model="accountFormData.verify" placeholder="请输入验证码">
              <img slot="prefix" src="~/assets/images/login-verify-icon.png" alt=""
                   style="width: 16px; height: 20px;">
            </m-input>

            <img @click="imgCaptcha()" class="captchaimg verify" :src="userInfo.imgurl" alt="">
          </div>
        </m-form-item>

        <div class="forget">
          <router-link to="/login-register/forget">忘记密码？</router-link>
        </div>

        <m-form-item>
          <div style="display: flex; justify-content: center;">
            <m-button width="235" @click="accountLogin" @keyup.enter="accountLogin">登录</m-button>
          </div>
        </m-form-item>
      </m-form>
      <router-link to="/login-register/register" class="to-register">没有账号？立即注册</router-link>
      <router-link to="" @click.native="showScan = true" class="scan-login">
        <img src="~/assets/images/wechat1.png" alt="">微信扫码登录
      </router-link>
    </div>

    <!-- 扫码 -->
    <div v-show="showScan" class="scan">
      <img class="close-icon" src="~/assets/images/close1.png" alt="" @click="showScan = false">
      <!-- <div class="title">微信扫码登录</div> -->
      <div class="qr" ref="qrCodeUrl" id="login_container">
        <!-- 承载二维码容器 -->
      </div>
      <!-- <div class="prompt">使用微信扫码即可登录</div> -->
      <div class="agreement">扫码即表示已阅读并接受
        <router-link to="" @click.native="showAgreement = true">《用户协议》</router-link>
      </div>
    </div>

    <!-- 协议 -->
    <div v-if="showAgreement" class="agreement-panel">
      <img class="close-icon" src="~/assets/images/close1.png" alt="" @click="showAgreement = false">
      <div class="title">{{rules.title}}</div>
      <div class="text" v-html="rules.content" />
    </div>
  </div>
</template>

<script>
import { mapMutations} from 'vuex'
import { password, emailPhone } from '@/utils/validates'
import MForm from '@/components/common/m-form/MForm'
import MFormItem from '@/components/common/m-form/MFormItem'
import MInput from '@/components/common/m-input/MInput'
import MButton from '@/components/common/m-button/MButton'
import { loginUser, phonelogin, getImgCaptcha, getPhoneCaptcha, platformRules } from '@/request/api'

export default {
  name: 'Login',
  components: { MForm, MFormItem, MInput, MButton },
  data() {
    const twice = (rule, val, cb) => {
      if (val !== this.formData.password) {
        cb(new Error('两次密码不同'))
      } else if (!val) {
        cb(new Error('请重复输入密码'))
      } else {
        cb()
      }
    }
    return {
      active: 1,
      mobileFormData: {},
      accountFormData: {},
      rules: {
        mobile: [{ validator: emailPhone, trigger: 'blur' }],
        password: [{ validator: password, trigger: 'blur' }],
        twice: [{ validator: twice, trigger: 'change' }],
        verify: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        msg: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }]
      },
      showScan: false,
      showAgreement: false,
      flag: false,
      content: '获取短信验证码',
      totalTime: 60,
      userInfo: {
        imgurl: null
      },
      imgkey: "",
      rules:{}
    }
  },
  created() {
    this.imgCaptcha()
    const t = this
    document.onkeydown = function (e) {
      let key
      if (window.event == undefined) {
        key = e.keyCode
      } else {
        key = window.event.keyCode
      }
      //enter的ASCII码是13
      if (key == 13) {
        t.accountLogin()
      }
    }
    if (this.$store.state.hasLogin) {
      this.$router.push('/home')
    }
  },
  mounted() {
    this.get_wx_qrcode()
    this.getRules()
  },
  methods: {
    ...mapMutations(['login', 'setUserInfo', 'setAccessToken']),
    phoneCaptcha() {
      let that = this
      let phone = this.mobileFormData.mobile
      if (!phone) {
        that.$toast.show('请填写手机号', 1000, false)
      } else if (!/^((1[3,5,8,7,9][0-9])|(14[5,7])|(17[0,6,7,8])|(19[1,7]))\d{8}$/.test(phone)) {
        that.$toast.show('请填写正确的手机号', 1000, false)
      } else {
        getPhoneCaptcha({
          phone: this.mobileFormData.mobile,
          type: 'login',
          code: '',
          key: ''
        }).then(res => {
          if (res.status === 200) {
            this.flag = true
            this.content = this.totalTime + 's后重新发送'
            let clock = window.setInterval(() => {
              this.totalTime--
              this.content = this.totalTime + 's后重新发送'
              if (this.totalTime < 0) {
                window.clearInterval(clock)
                this.content = '重新发送验证码'
                this.totalTime = 60
                this.flag = false
              }
            }, 1000)
          } else {
            that.$toast.show(res.message, 1000, false)
          }
        })
      }
    },
    mobileLogin() {
      let that = this
      this.$refs.form1.$refs.mForm.validate(valid => {
        if (valid) {
          let data = {
            phone: this.mobileFormData.mobile,
            sms_code: this.mobileFormData.msg,
            img_code: this.mobileFormData.verify,
            key: this.imgkey
          }
          phonelogin(data).then(res => {
            if (res.status === 200) {
              that.loginSuc(res)
            } else {
              that.$toast.show(res.message, 1000, false)
              that.mobileFormData = {}
              that.imgCaptcha()
            }
          }).catch(err => {
            that.$message.error(err.message)
          })
        }
      })
    },
    imgCaptcha() {
      getImgCaptcha().then(res => {
        this.userInfo.imgurl = res.data.captcha
        this.imgkey = res.data.key
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    accountLogin() {
      let that = this
      this.$refs.form2.$refs.mForm.validate(valid => {
        if (valid) {
          let data = {
            account: this.accountFormData.mobile,
            password: this.accountFormData.password,
            captcha: this.accountFormData.verify,
            key: this.imgkey
          }
          loginUser(data).then(res => {
            if (res.status === 200) {
              that.loginSuc(res)
            } else {
              that.$toast.show(res.message, 1000, false)
              that.accountFormData = {}
              that.imgCaptcha()
            }
          }).catch(err => {
            this.$message.error(err.message)
          })
        }
      })
    },
    loginSuc(res) {
      //vuex状态更新，数据存入缓存
      this.setUserInfo(res.data.user)
      this.setAccessToken(res.data.token)
      this.login()
      this.$toast.show('登录成功!', 1000, false)
      let that = this
      setTimeout(function () {
        that.$router.push({ path: '/home' })
      }, 1000)
    },
    goWXLogin() {
      this.showScan = true
    },
    // 前端调起微信授权登录
    get_wx_qrcode() {
      //从微信的开发文档不难看出回调域名需要经过encodeURIComponent处理
      const obj = new WxLogin({
        self_redirect: false,  //值为true时，直接在二维码的弹窗中进行页面跳转及其余操作,
        id: 'login_container',       //需要承载二维码的容器id
        appid: 'wx0b12bc5f78a50ddc',
        scope: 'snsapi_login',     //网页授权，目前网页只有这一种方式，静默授权
        redirect_uri: encodeURIComponent('http://www.pack-mate.com/#/login-register/bind'),     //回调域名(地址前部分是项目域名，后部分loginSuccess是微信需要跳转的路径（vue中的路由名称）)
        state: Math.random(),
        style: 'black',
        href: ''
      })
    },
    getRules() {
      platformRules(2).then(res => {
        this.rules = res.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/style/common.scss";

.login {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;

  .label-wrap {
    display: inline-flex;
    align-items: center;

    .label-text {
      font-size: 16px;
      color: #969696;
    }

    .label-icon {
      margin-right: 10px;
    }
  }

  .swiper {
    width: 440px;
    display: flex;
    margin-bottom: 60px;

    .swiper-item {
      width: 50%;
      height: 55px;
      line-height: 55px;
      text-align: center;
      color: #666;
      font-size: 18px;
      border-bottom: solid 1px $theme-color-1;
      cursor: pointer;

      &.active {
        color: $theme-color-1;
        border-bottom-width: 2px;
      }
    }
  }

  .forget {
    color: #969696;
    margin-bottom: 30px;
    display: flex;
    justify-content: flex-end;
  }

  .to-register {
    display: block;
    text-align: center;
    color: $theme-color-1;
    margin-bottom: 30px;
  }

  .scan-login {
    color: #969696;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      margin-right: 5px;
    }
  }

  .scan {
    position: absolute;
    top: calc(50% - 241px);
    left: calc(50% - 216px);
    width: 432px;
    height: 483px;
    background-color: #fff;
    border: solid 1px #eaeaea;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .close-icon {
      position: absolute;
      top: 15px;
      right: 15px;
      cursor: pointer;
    }

    .title {
      font-weight: bold;
      font-size: 22px;
      color: #969696;
      margin-top: 80px;
      margin-bottom: 20px;
    }

    .qr {
      display: flex;
      color: #4a4a4a;
      justify-content: center;
      align-items: center;
      margin: 0 auto 25px;
    }
    /deep/ iframe {
      width: 300px !important;
      height: 380px !important;
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }

    .prompt {
      margin-bottom: 40px;
      color: #969696;
    }

    .agreement {
      color: #969696;

      a {
        color: $theme-color-1;
      }
    }
  }

  .agreement-panel {
    position: absolute;
    top: calc(50% - 265px);
    left: calc(50% - 300px);
    z-index: 99;
    width: 600px;
    height: 530px;
    background-color: #fff;
    border: solid 1px #eaeaea;
    display: flex;
    flex-direction: column;
    align-items: center;

    .close-icon {
      position: absolute;
      top: 15px;
      right: 15px;
      cursor: pointer;
    }

    .title {
      margin-top: 30px;
      font-size: 18px;
      color: #969696;
    }

    .text {
      width: 100%;
      height: 350px;
      padding: 0 50px;
      font-size: 16px;
      overflow-y: auto;
      color: #969696;
      // line-height: 35px;
    }

  }
}

.captchaimg {
  width: 130px;
  height: 45px;
}
</style>
